package com.example.concurrent.chapter03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author Create By Liuqz
 * @date 2018/11/20 15:41
 */
public class FightQueryExample {


    private static List<String> fightCompany = Arrays.asList("CSA","CEA","HNA");

    public static void main(String[] args) {
        List<String> results = search("SH","BJ");
        System.out.println("=========result=========");
        results.forEach(System.out::println);
    }

    private static List<String> search(String original, String dest) {
        final List<String> result = new ArrayList<>();

        //2.创建查询航班信息的线程列表
        List<FightQueryTask> fightQueryTasks = fightCompany.stream().map(f -> createSearchTask(f, original, dest)).collect(toList());

        //3.启动这些线程
        fightQueryTasks.forEach(Thread::start);

        //4.分别调用每个线程的join方法,阻塞当前线程
        fightQueryTasks.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        //5.在此之前,当前线程会阻塞住,获取每一个查询线程的结果,并且加入到result中
        fightQueryTasks.stream().map(FightQuery::get).forEach(result::addAll);
        return result;
    }

    private static FightQueryTask createSearchTask(String fight,String origin,String dest) {
        return new FightQueryTask(fight, origin, dest);
    }
}
